#install.packages("SDMTools")
library(data.table)
library(stargazer)
library(SDMTools)
library(Hmisc)
library(foreign)

### Wagner niche-ness mesure

data <- read.dta("1999-2010_CHES_dataset_means.dta")

data<-data[data$year>2006,]

# Calculate mean weighted salience of all parties on econ issue

mean.econ <- wtd.mean(data$spendvtax_salience,data$vote,na.rm=T)

# Centre around weighted mean

data$weighted.econ <- data$spendvtax_salience - mean.econ

# Calculate mean weighted salience of all parties on EU

mean.eu <- wtd.mean(data$eu_salience,data$vote,na.rm=T)

# Centre around weighted mean

data$weighted.eusal <- data$eu_salience - mean.eu

# Create econ niche cutoff with weighted sd

data$econ.niche <- data$weighted.econ < mean(data$weighted.econ,na.rm=T) - wt.sd(data$spendvtax_salience,data$vote)

# Create EU niche cutoff with weighted sd

data$eu.niche <- data$weighted.eusal - wt.sd(data$eu_salience,data$vote) > mean(data$weighted.eusal,na.rm=T)

data$niche <- data$eu.niche & data$econ.niche

#model <- lm(eu_dissent ~ niche,data=data)

#TABLE 4: EU dissent
model <- lm(eu_dissent ~ eu.niche,data=data)

stargazer(model,report=c("vct"))











# Calculate mean weighted position of all parties on eu issue

mean.eu.pos <- wtd.mean(data$position,data$vote,na.rm=T)

# Centre around weighted mean

data$weighted.eu.pos <- data$position - mean.eu.pos

# Create eu.pos niche cutoff with weighted sd

data$eu.pos.niche <- data$weighted.eu.pos < mean(data$weighted.eu.pos,na.rm=T) - wt.sd(data$position,data$vote)

summary(lm(eu_dissent ~ eu.pos.niche,data=data))




# Eurosceptics
data <- read.csv("CHES_2010_expert_data_public.csv")
#data <- read.dta("~/Desktop/CHES_2010_expert_data_public (2).dta")
data.trend <- read.dta("1999-2010_CHES_dataset_means.dta")

data <- data.table(data)
eu.pos <- data[,list(V1=mean(eu_pos,na.rm=T),dissent=mean(eu_dissent,na.rm=T)),by=party_id]
eu.pos <- data.frame(eu.pos)
party.names<- data.trend[,c("party_id","party")]

eu.pos$party <- party.names$party[match(eu.pos$party_id,party.names$party_id)]

mean.eu.pos <- mean(eu.pos$V1)
eu.pos$weighted.eu.pos <- eu.pos$V1 - mean.eu.pos
eu.pos$eu.niche <- eu.pos$weighted.eu.pos < mean(eu.pos$weighted.eu.pos,na.rm=T) - sd(eu.pos$V1)

summary(lm(dissent ~ eu.niche,data=eu.pos))